package
{
	import com.adobe.serialization.json.*;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.*;
	import flash.utils.Dictionary;
	
	import org.flixel.*;
	
	// extends sprite just so we can dispatch events.
	public class FaceBook extends Sprite
	{
		// Directory where we'll grab the php webservice files
		public static const FB_SERVICE_DOMAIN:String = "http://games.cs.washington.edu/capstone/11sp/elemental/logs/test/";// event constants
		
		// event constant
		public static const FRIENDS_LOADED:String = "FRIENDS LOADED";
		public static const INFO_LOADED:String = "INFO LOADED";
		
		// replace this debugging access token with your own
		public static const ACCESS_TOKEN:String = "2227470867|2.AQA4EA1P2NonFa5c.3600.1307736000.0-555437232|raQGqIRkZafRsOViXm1Rraru8FM";
		
		public var userName:String;
		public var userID:String;
		public var fullName:String;
		public var friends:Array;
		public var token:String;
		
		private var idToFullName:Dictionary;
		
		public function FaceBook(usrName:String, usrID:String, name:String, accessToken:String)
		{
			fullName = name;
			userName = usrName;
			userID = usrID;
			token = accessToken;
		}
		
		//takes a facebook id and asks for the profile picture of that id.
		public function addPicture(id:String, callback:Function):void{
			var url:String = FB_SERVICE_DOMAIN + "getPicture.php?id=" + id +"&type=square";
			var urlRequest:URLRequest = new URLRequest(url);
			var loader:Loader = new Loader(); 
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, callback);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, Client.onIOError);
			loader.load(urlRequest);
		}
		
		/**
		 * Example image loaded callback
		 */
		public function imgLoaded(e:Event):void {
			var img:Bitmap = new Bitmap(e.target.content.bitmapData);
			var sprite:FlxSprite = new FlxSprite(200,10);
			sprite.pixels = img.bitmapData;
		}
		

		/**
		 * Get a list of all friends of the currently logged in user
		 */
		public function getFriends():void{
			var urlRequest:URLRequest = new URLRequest(FB_SERVICE_DOMAIN + "getFriend.php?access_token=" + token);
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			urlLoader.addEventListener(Event.COMPLETE, friendRequestResponse);
			urlLoader.load(urlRequest);
			trace("sent getFriends request");
		}
		
		/**
		 * Get a list of all friends of the currently logged in user
		 */
		private function friendRequestResponse(e:Event):void{
			var urlLoader:URLLoader = URLLoader(e.target);
			var serverReply:String = urlLoader.data;
			if (serverReply.length > 0){
				var arr:Object = JSON.decode(serverReply);
				friends = arr["data"] as Array;
				trace("num friends = " + friends.length);
				
				if (friends == null) {
					friends = new Array();
				}
				Client.filterIDs(friends, onFilterResponse);
				trace("send data to be filtered");
			} 
		}
		
		/**
		 * Handler for Client.filterIDs
		 */
		private function onFilterResponse(e:Event):void {
			trace("received filtered ids");
			var ids:String = e.target.data;
			var temp:Array = ids.split(":");
			temp.pop(); // because the last element is always empty or something.
			
			var ffriends:Array = new Array();
			idToFullName = new Dictionary();
			for (var i:int = 0; i < friends.length; i++) {
				var id:String = friends[i]["id"];
				if (temp.indexOf(id) != -1) {
					var obj:Object = new Object();
					obj["id"] = id;
					obj["name"] = friends[i]["name"];
					ffriends.push(obj);
					idToFullName[id] = friends[i]["name"];
					trace("adding " + friends[i]["name"]);
				}
			}
			friends = ffriends;
			dispatchEvent(new Event(FRIENDS_LOADED, true));
		}

		/**
		 * Given an id, retrieve the friend's first/last name
		 */
		public function getFriendInfo(id:String, callback:Function):void{
			var urlRequest:URLRequest = new URLRequest(FB_SERVICE_DOMAIN + "getInfo.php?id=" + id);
			var urlLoader:URLLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.TEXT; // default
			urlLoader.addEventListener(Event.COMPLETE, callback);
			urlLoader.load(urlRequest);
		}
		
		/**
		 * Example callback for getFriendInfo()
		 */
		private function infoLoaded(e:Event):void{
			var urlLoader:URLLoader = URLLoader(e.target);
			var serverReply:String = urlLoader.data;
			if (serverReply.length > 0){
				var obj:Object = JSON.decode(serverReply);
				var evn:Event = new InfoEvent(INFO_LOADED,obj,true);
				dispatchEvent(evn);
			}
		}
		
		//calls this to sent a request to a friend
		// to = facebook id of the friend where this request goes to
		// message = the message to be displayed with this request
		// data = any special data associated with this request
		public function sentRequest(message:String, to:String = null,data:String = null):void{
			var toCode:String ="";
			var dataCode:String = "";
			if (to != null){
				toCode = "&to="+to;
			}
			if (data != null){
				dataCode = "&data="+data;
			}
			var urlRequest:URLRequest = new URLRequest(FB_SERVICE_DOMAIN + "sentRequest.php?message="+message
					+toCode+dataCode);
			navigateToURL(urlRequest, "_top");	
		}

		/**
		 * Getters
		 */
		public function get accessToken():String { return token; }
		
		/**
		 * Returns full name from friend id.  Assumes the id passed
		 * is one of your Poofed existing friends
		 */
		public function getFullNameFromID(id:String):String {
			if (id in idToFullName) {
				return idToFullName[id];
			} else {
				return "";
			}
		}
	}
}